package crm.model.teacherPC.connectList;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import crm.model.Setting;
import crm.model.teacherPC.Manager;
import crm.model.teacherPC.net.StudentPC;



public class StudentPcFinder {
	public static void find(Manager manager){
		try {


			DatagramSocket udpSocket = new DatagramSocket();
			udpSocket.setBroadcast(true);
			byte[] buffer = new byte[0];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(Setting.getString("Net.Broadcast")), Setting.getSendPort());
			udpSocket.send(packet);
			udpSocket.close();
			ArrayList <StudentPC>list = new ArrayList<StudentPC>();


			while (true){

				ServerSocket ss = initServer();

				ss.setSoTimeout(20000);
				Socket s;

				try {
					s = ss.accept();
				}catch (SocketTimeoutException e) {
					ss.close();
					System.out.println("no ohter Students founded");
					break;
				}
				StudentPC student = connect(s, manager);

				manager.addStudent(student);
				ss.close();

			}

		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	public static ServerSocket initServer() {

		ServerSocket ss = null;
		try {
			ss = new ServerSocket(Setting.getTransportPort());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ss;
	}
	public static synchronized StudentPC connect(Socket s, Manager manager) {
		ConnectStudent conS = Manager.connectingStudent.get(s.getInetAddress().getHostAddress());
		StudentPC student = null;
		if (conS == null){
			student = new StudentPC(s, manager);
			Manager.connectingStudent.put(s.getInetAddress().getHostAddress(), new ConnectStudent(s.getInetAddress().getHostAddress(), "keine Information vorhanden", true, student));
		}
		else {
			student = conS.connect(s, manager);
		}
		return student;
	}
















}
